<template>
  <div
    :class="['notice-item', { 'notice-unread': noticeItem.isRead === 0 }]"
    @click="handleClick"
  >
    <!-- 聚合通知：显示多个头像 -->
    <div
      v-if="noticeItem.isGrouped && noticeItem.senders"
      class="notice-avatars"
    >
      <el-avatar
        v-for="(sender, index) in noticeItem.senders.slice(0, 3)"
        :key="sender.userId"
        :size="32"
        :src="formatAvatarUrl(sender.avatar)"
        :style="{ zIndex: 3 - index, marginLeft: index > 0 ? '-8px' : '0' }"
        class="stacked-avatar"
      >
        <template #default>
          <el-icon><User /></el-icon>
        </template>
      </el-avatar>
      <span v-if="(noticeItem.count || 0) > 3" class="more-count">
        +{{ (noticeItem.count || 0) - 3 }}
      </span>
    </div>

    <!-- 普通通知：显示单个头像 -->
    <el-avatar v-else :size="40" :src="formattedAvatar" class="notice-avatar">
      <template #default>
        <el-icon><User /></el-icon>
      </template>
    </el-avatar>

    <div class="notice-content">
      <div class="notice-title">
        {{ noticeItem.title }}
        <el-badge
          v-if="noticeItem.unreadCount && noticeItem.unreadCount > 0"
          :value="noticeItem.unreadCount"
          :max="99"
          type="danger"
        />
        <el-badge v-else-if="noticeItem.isRead === 0" is-dot />
      </div>
      <div class="notice-description">
        {{ noticeItem.description }}
      </div>
      <div class="notice-time">
        {{ formatTime(noticeItem.datetime) }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { PropType, computed } from "vue";
import { useRouter } from "vue-router";
import { User } from "@element-plus/icons-vue";
import type { NoticeListItem } from "./types";
import { markNotificationAsReadApi } from "@/api/notification";
import { formatAvatarUrl } from "@/utils/avatar";

const props = defineProps({
  noticeItem: {
    type: Object as PropType<NoticeListItem>,
    required: true
  }
});

const emit = defineEmits(["refresh"]);
const router = useRouter();

/** 格式化后的头像URL */
const formattedAvatar = computed(() => {
  return formatAvatarUrl(props.noticeItem.avatar);
});

/** 格式化时间显示 */
const formatTime = (time: string) => {
  if (!time) return "";

  const now = new Date();
  const noticeTime = new Date(time);
  const diff = now.getTime() - noticeTime.getTime();

  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return time.split(" ")[0]; // 返回日期部分
};

/** 点击通知项 */
const handleClick = async () => {
  const messageType = props.noticeItem.type;

  console.log("📩 点击通知消息,跳转到对应选项卡", {
    id: props.noticeItem.id,
    title: props.noticeItem.title,
    type: messageType
  });

  try {
    // 如果是未读通知，标记为已读
    if (
      props.noticeItem.isRead === 0 &&
      typeof props.noticeItem.id === "number"
    ) {
      await markNotificationAsReadApi(props.noticeItem.id);
      emit("refresh");
    }

    // 根据消息类型构建跳转URL
    // 消息中心使用 hash 参数来切换选项卡
    let targetUrl = "/user/messages";

    if (messageType) {
      // 添加消息类型作为 hash 参数,消息中心会自动切换到对应选项卡
      targetUrl = `/user/messages#${messageType}`;
      console.log(`✅ 跳转到消息中心的 ${messageType} 选项卡`);
    }

    await router.push(targetUrl);
    console.log("✅ 已跳转到消息中心");
  } catch (error) {
    console.error("❌ 处理通知点击失败:", error);
  }
};
</script>

<style lang="scss" scoped>
.notice-item {
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f9fafb;
  }

  &.notice-unread {
    background-color: #f0f9ff;

    &:hover {
      background-color: #e1f3ff;
    }
  }

  .notice-avatar {
    flex-shrink: 0;
  }

  .notice-avatars {
    position: relative;
    display: flex;
    flex-shrink: 0;
    align-items: center;

    .stacked-avatar {
      border: 2px solid #fff;
      transition: transform 0.2s ease;
    }

    .more-count {
      margin-left: 8px;
      font-size: 13px;
      color: #6b7280;
      white-space: nowrap;
    }
  }

  .notice-content {
    flex: 1;
    min-width: 0;

    .notice-title {
      display: flex;
      gap: 8px;
      align-items: center;
      margin-bottom: 4px;
      font-size: 14px;
      font-weight: 500;
      color: #1f2937;
    }

    .notice-description {
      display: -webkit-box;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      font-size: 13px;
      line-height: 1.5;
      color: #6b7280;
      -webkit-box-orient: vertical;
    }

    .notice-time {
      font-size: 12px;
      color: #9ca3af;
    }
  }
}
</style>
